package com.encuestas;



import com.gio.lib.conexion.conectividad;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.widget.Toast;



/*
 * esta servicio notifica cuando el servicio de internet es suspendido a la actividad
 * 
 * 
 * 
 * 
 * */
public class servicioInternet extends Service implements Callback, Runnable{
	private static boolean isRunning = false;

	conectividad con;
	private Messenger activity;

	private Messenger servicio;
	Thread tarea;

	public static final int CONECTAR = 0;
	public static final int DESCONECTAR = 1;
	public static final int MENSAJE = 2;

	@Override
	public void onCreate() {

		super.onCreate();
		con= new conectividad(this);
		servicio = new Messenger(new Handler(this));

		isRunning=true;
		tarea= new Thread(this);


	}

	@Override
	public void onDestroy() {

		super.onDestroy();
		if(tarea.isAlive())
		{
			tarea.interrupt();


		}
		isRunning=false;

	}

	public boolean handleMessage(Message msg) {

		switch (msg.what) {
		case CONECTAR:


			activity=msg.replyTo;
			Message msn = new Message();
			msn.obj="te respondo desde el servicio";
			msn.what= CONECTAR;
			tarea.start();


			try
			{
				activity.send(msn);


			}
			catch
			(RemoteException ex)
			{

			}





			break;

		case DESCONECTAR:
			activity = null;
			break;


		case MENSAJE:
			Toast.makeText(this, (String)msg.obj, Toast.LENGTH_SHORT).show();

			break;

		default:
			break;
		}



		return true;

	}

	@Override
	public IBinder onBind(Intent intent) {

		return servicio.getBinder();
	}



	public static boolean isRunning() {
		return isRunning;
	}





	public void run() {


		while (true) {

			try {
				Thread.sleep(10000);

				if(con.CheckConectivityWifi())
				{

					Message m = new Message();
					m.what = MENSAJE;
					m.obj = "internet o . k . ";
					if(activity!= null)
					{
						try {
							activity.send(m);
						} catch (RemoteException e) {

							e.printStackTrace();
						}

					}
					else
					{
						servicio.send(m);
					}



				}

				else
				{
					Message m = new Message();
					m.what = MENSAJE;
					m.obj = "internet fail";
					if(activity!= null)
					{
						try {
							activity.send(m);
						} catch (RemoteException e) {

							e.printStackTrace();
						}

					}
					else
					{
						servicio.send(m);
					}


				}


			} catch (InterruptedException e) {

				e.printStackTrace();
			} catch (RemoteException e) {

				e.printStackTrace();
			}

		}

	}


}
